import React, { useCallback } from 'react';
import { history } from 'ice';
import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { Dropdown } from 'antd';
import styles from './index.module.css';
import store from '@/store';
import { notification } from 'antd';

interface AvatarDropdownProps {
  name: string;
}
enum MenuKey {
  USER_CENTER = 'userCenter',
  LOGOUT = 'logout'
}

const AvatarDropdown: React.FC<AvatarDropdownProps> = ({ name }) => {
  const [, userDispatcher] = store.useModel('user');

  const loginOut = async () => {
    sessionStorage.removeItem('token');
    history?.push({
      pathname: '/login',
    });
    notification.success({
      message: '退出成功',
      duration: 1.5,
    });

  };

  const onMenuClick = useCallback((event) => {
    const { key } = event;
    if (key === MenuKey.USER_CENTER) {
      history?.push('/userCenter')
    }
    if (key === MenuKey.LOGOUT) {
      userDispatcher.updateCurrentUser({});
      loginOut();
    }
  }, []);

  const menu = {
    items: [
      {
        key: MenuKey.USER_CENTER, label: '个人中心', icon: <UserOutlined />, onClick: onMenuClick, className: styles.menu,
      },
      {
        key: MenuKey.LOGOUT, label: '退出登录', icon: <LogoutOutlined />, onClick: onMenuClick, className: styles.menu,
      },
    ],
  };
  return (
    <Dropdown menu={menu}>
      <span className={`${styles.action} ${styles.account}`}>
        <span>欢迎您，</span>
        <span>{name}</span>
      </span>
    </Dropdown>
  );
};

export default AvatarDropdown;
